package br.com.openari.fretedroidbh;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;

import android.util.Log;

public class Calcular {
	
	private Frete frete;
	
	
	public Calcular(String cep, String comprimento, String peso, String altura, String largura){
		
		frete = new Frete();
		
		frete.setCep(cep);
		frete.setComprimento(comprimento);
		frete.setPeso(peso);
		frete.setAltura(altura);
		frete.setLargura(largura);		
	}
	
	public Frete calcularFrete() {
		
		Frete aux = null;
		
		try {
		
			URL url = new URL(montarLink().toString());
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();			
			
			conn.setRequestProperty("Request-Method","GET"); 
			 
			conn.setDoInput(true);
			conn.setDoOutput(false);

			conn.connect();
			
			// abre a conexao pra input
			aux = parser(new InputStreamReader(conn.getInputStream()));			
			
			conn.disconnect();
			
		
		} catch (MalformedURLException e) {			
			Log.e("#ERRO: ", e.getMessage(), e);
			
		} catch (IOException e) {		
			Log.e("#ERRO: ", e.getMessage(), e);
			
		} catch (Exception e) {			
			Log.e("#ERRO: ", e.getMessage(), e);			
		}
		
		return aux;
	}

	private StringBuffer montarLink() {
		StringBuffer link = new StringBuffer();
		
		link.append(Frete.getUrl());
		link.append("cep=");
		link.append(frete.getCep());
		link.append("&cod=");
		link.append(Frete.getCodigo());
		link.append("&peso=");
		link.append(frete.getPeso());
		link.append("&comprimento=");
		link.append(frete.getComprimento());
		link.append("&largura=");
		link.append(frete.getLargura());
		link.append("&altura=");
		link.append(frete.getAltura());
		link.append("&servico=");
		link.append(Frete.getServico());
		
		return link;
	}
	
	private Frete parser(InputStreamReader in) throws Exception{		
		
		KXmlParser parser = new KXmlParser();
		parser.setInput(in);
		
		parser.nextTag();
		
		parser.require(XmlPullParser.START_TAG, null, "frete");
		
		while(parser.nextTag() != XmlPullParser.END_TAG){
			
			parser.require(XmlPullParser.START_TAG, null, null);
			String name = parser.getName();
			String text = parser.nextText();
			
			if("uf".equals(name)){
				frete.setUf(text);				
			}
			
			parser.require(XmlPullParser.END_TAG, null, name);
			
		}
		
		parser.require(XmlPullParser.END_TAG, null, "frete");
		parser.next();
		parser.require(XmlPullParser.END_DOCUMENT, null, null);
		
		return frete;
	}

}
